﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MiniFox.Infrastructure;

namespace MiniFox.Web.Filters
{
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ValidationFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            var modelState = filterContext.ModelState;
            if (!modelState.IsValid)
            {
                var state = modelState.Values.First(p => p.Errors.Count > 0);
                var error = state.Errors[0];
                filterContext.Result = new JsonResult(new ErrorResponse(error.Exception ?? new MiniFox.Exceptions.SystemException(error.ErrorMessage)));
            }
            else
            {
                await base.OnActionExecutionAsync(filterContext, next);
            }
        }
    }
}
